﻿using System;
using System.Web;
using MAF.Common;

namespace MAF.UserSecurity
{
    /// <summary>
    /// Web认证员
    /// </summary>
    internal class WebAuthenticator : Authenticator
    {
        /// <summary>
        /// 客户端记录登录上下文
        /// </summary>
        /// <param name="isKeepLogon"></param>
        /// <param name="gotoHere"></param>
        protected override void LogUserOnClient(UserContext context, DateTime expired)
        {
            HttpContext c = HttpContext.Current;
            c.User = context;

            // 创建Cookies
            HttpCookie ckSID = new HttpCookie(SecurityConst.SID, context.Token.ToString());
            HttpCookie ckUID = new HttpCookie(SecurityConst.UID, context.User.Id.ToString());
            ckSID.Expires = ckUID.Expires = expired;

            // 发送到客户端
            c.Response.Cookies.Add(ckSID);
            c.Response.Cookies.Add(ckUID);
        }

        /// <summary>
        /// 客户端注销登录上下文
        /// </summary>
        /// <param name="token"></param>
        protected override void LogUserOutClient(Guid token)
        {
            HttpContext c = HttpContext.Current;
            c.User = null;

            // 创建Cookies
            HttpCookie ckSID = new HttpCookie(SecurityConst.SID, string.Empty);
            HttpCookie ckUID = new HttpCookie(SecurityConst.UID, string.Empty);
            ckSID.Expires = ckUID.Expires = DateTime.Now.AddYears(-10);

            // 发送到客户端
            c.Response.Cookies.Add(ckSID);
            c.Response.Cookies.Add(ckUID);
        }

        /// <summary>
        ///  在客户端保持登陆状态
        /// </summary>
        /// <param name="token"></param>
        protected override void KeepUserLogOnClient(Guid token)
        {
            HttpContext.Current.User = ActiveUsers[token];
        }
    }
}